package com.spring.demo.web.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.spring.demo.core.entity.Ping;
import com.spring.demo.core.service.IPingService;
import com.spring.demo.web.validator.PingValidator;

@Controller
@RequestMapping("/ping")
public class PingController {

	@Autowired
	private IPingService pingService;
	@Autowired
	private PingValidator pingValidator;

	@InitBinder
	public void initBinder(WebDataBinder binder) {
		binder.setValidator(pingValidator);
	}

	@RequestMapping("/list")
	public String list(Model model) {

		List<Ping> pings = pingService.getPings();
		model.addAttribute("pings", pings);
		return "ping/list";
	}

	@RequestMapping("/show")
	public String show(Long id, Model model) {
		Ping ping = null;
		if (id != null) {
			ping = pingService.findPingById(id);
		} else {
			ping = new Ping();
		}
		model.addAttribute("ping", ping);
		return "ping/show";
	}
	
	/**
	 * rest test
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/rest")
	@ResponseBody
	public Ping rest(Long id) {
		Ping ping = pingService.findPingById(id);
		return ping;
	}

	@RequestMapping("/delete/{id}")
	public String delete(@PathVariable Long id) {

		boolean result = pingService.deletePingById(id);
		assert result == true;
		return "redirect:/ping/list";
	}

	@RequestMapping(value = "/createOrUpdate", method = RequestMethod.POST)
	public String createOrUpdate(@Validated Ping ping, BindingResult result) {
		if (result.hasErrors()) {
			return "ping/show";
		}
		pingService.saveOrUpdatePing(ping);

		return "redirect:./list";
	}
}
